package com.example.demo.config;

import com.example.demo.common.AjaxResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/*
实现 统一数据返回的保底类
即在返回数据之前，检测数据的类型是否是统一对象，如果不是，则封装成统一的对象
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    @Autowired
    private ObjectMapper objectMapper;
    // 开关，唯有返回值为true时才会进行beforeBodyWrite的调用
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }
    /*
    对数据格式进行校验和封装
     */
    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //是统一的数据格式
        if(body instanceof AjaxResult){
            return body;
        }
        //如果是字符串类型，我们需要引入ObjectMapper进行数据的处理，将其处理为json格式
        if(body instanceof String){
                return objectMapper.writeValueAsString(AjaxResult.success(body));
        }
        return AjaxResult.success(body);
    }
}
